package com.dreamwhale.machinery.utils;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @ClassName : AliSms
 * @Description :
 * @Author : DragonUncle
 * @Date :  10:00 2020/4/24
 */
@Component
public class AliSmsUtils {
    @Autowired
    private AliSmsConfig aliSmsConfig;

    @Data
    public static class Sms {
        private String message;
        private String requestId;
        private String bizId;
        private String code;
    }

    /**
     * @param : telephone   手机号
     * @param : body        内容需要在类中有code字符赋值转json
     * @return :
     * @MethodName : toSend
     * @Description : 发送短信  阿里云短信的规定是直接传入code即可不需要自己手动输入全部内容
     * 所以使用一个类或者一个map转json即可
     * @Author : DragonUncle
     * @Data : 10:58 2020/4/24
     */
    public Boolean toSend(String telephone, String templateCode, String body) {
        String regionId = aliSmsConfig.getRegionId();
        String accessKeyId = aliSmsConfig.getAccessKeyId();
        String secret = aliSmsConfig.getSecret();
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysDomain(aliSmsConfig.getDomain());
        request.setSysVersion(aliSmsConfig.getVersion());
        request.setSysAction(aliSmsConfig.getAction());
        request.putQueryParameter("SignName", aliSmsConfig.getSignName());//短信签名
        request.putQueryParameter("TemplateCode", templateCode);//短信模板
        request.putQueryParameter("PhoneNumbers", telephone);//传过来的手机号
        request.putQueryParameter("TemplateParam", body);//随机生成的6位数验证码
        try {
            CommonResponse response = client.getCommonResponse(request);
            Sms sms = JSON.parseObject(response.getData(), Sms.class);//解析json格式的内容
            return sms.getCode().equals("OK"); //判断code返回的数据是否为OK
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
